package development;

import state.DrawListener;
import state.GameConstants;
import state.GameForm;
import state.Graphics;
import state.Key;
import state.Sprite;
import state.component.BottomBar;
import state.component.Checkbox;
import state.component.Event;
import state.component.EventListener;
import state.component.GameMenu;
import state.component.TextField;
import state.font.FontManager;
import state.font.ImageFont;
import state.util.GameColor;
import state.util.GameStringUtils;
import state.util.Hashtable;
import development.bean.User;
import development.group.FrmGroupFriendAndTop;
import development.group.FrmGroupMenu;
import development.group.FrmGroupNapXuAndExchangeGold;
import development.socket.SocketClientUtil;

public class FrmUserInfo extends GameForm implements EventListener {
  private TextField statusTextField;
  private TextField mobileTextField;
  private TextField fullNameTextField;
  private TextField dateOfBirthTextField;
  private TextField monthOfBirthTextField;
  private TextField yearOfBirthTextField;
  private TextField emailTextField;
  private TextField addressTextField;

  private Checkbox maleCheckbox;
  private Checkbox femaleCheckbox;

  private int chooseIndex;
  private int formDy;
  private ImageFont text8;
  private boolean isShowExtendInfo;

  public static GameForm goBackForm;

  private static GameForm singleton;

  private Hashtable parameters;
  private String account;

  public static GameForm instance() {
    if (singleton == null) {
      singleton = new FrmUserInfo();
    }
    return singleton;
  }

  public void init(Hashtable parameters1) {
    this.parameters = parameters1;
    if (parameters1 != null) {
      account = GameStringUtils.nvl(parameters1.get("User"), Global.currentUser.getName());
    } else {
      account = Global.currentUser.getName();
    }
    
    // Create bottom bar
    BottomBar bottomBar = DrawUtils.getBottomBar(_manager);
    if (account.equals(Global.currentUser.getName())) {
      bottomBar.setLabels("Menu", "", "Trở về");
      bottomBar.setLeftMenu("Menu", new GameMenu(null, new String[] { "Về menu chính", "Bạn bè", "Đổi mật khẩu", "Chọn avatar", "Đổi gold" }, 5, this, Constants.MENU_STYLE, 0, GameConstants.SCREEN_HEIGHT - 45));
    } else {
      bottomBar.setLabels("", "", "Trở về");
    }
    
    statusTextField = new TextField(_manager, TextField.CONSTRAINT_ANY, Constants.TEXT_FIELD_STYLE);
    statusTextField.setSize(156, 30);
    statusTextField.setPosition(60, 49);

    mobileTextField = new TextField(_manager, TextField.CONSTRAINT_NUMERIC, Constants.TEXT_FIELD_STYLE);
    mobileTextField.setSize(140, 20);
    mobileTextField.setPosition(73, 173);

    fullNameTextField = new TextField(_manager, TextField.CONSTRAINT_ANY, Constants.TEXT_FIELD_STYLE);
    fullNameTextField.setSize(140, 20);
    fullNameTextField.setPosition(73, 199);
    fullNameTextField.setText(account);

    dateOfBirthTextField = new TextField(_manager, TextField.CONSTRAINT_NUMERIC, Constants.TEXT_FIELD_STYLE).setMaxLength(2);
    dateOfBirthTextField.setSize(22, 20);
    dateOfBirthTextField.setPosition(140, 225);

    monthOfBirthTextField = new TextField(_manager, TextField.CONSTRAINT_NUMERIC, Constants.TEXT_FIELD_STYLE).setMaxLength(2);
    monthOfBirthTextField.setSize(22, 20);
    monthOfBirthTextField.setPosition(166, 225);

    yearOfBirthTextField = new TextField(_manager, TextField.CONSTRAINT_NUMERIC, Constants.TEXT_FIELD_STYLE).setMaxLength(4);
    yearOfBirthTextField.setSize(40, 20);
    yearOfBirthTextField.setPosition(193, 225);

    emailTextField = new TextField(_manager, TextField.CONSTRAINT_EMAIL_ADDRESS, Constants.TEXT_FIELD_STYLE);
    emailTextField.setSize(140, 20);
    emailTextField.setPosition(73, 252);

    addressTextField = new TextField(_manager, TextField.CONSTRAINT_ANY, Constants.TEXT_FIELD_STYLE);
    addressTextField.setSize(140, 38);
    addressTextField.setPosition(73, 279);

    maleCheckbox = new Checkbox(_manager, this, Constants.CHECK_BOX_STYLE, 69, 149 + formDy).setLabel("Nam");
    femaleCheckbox = new Checkbox(_manager, this, Constants.CHECK_BOX_STYLE, 128, 149 + formDy).setLabel("Nữ");

    text8 = FontManager.getFont(FontManager.FONT_SIZE_8);
    new Sprite(null, _manager, 0, 0, Constants.TOP_LEFT_ANCHOR).setDrawListener(new DrawListener() {
      public void paint(Sprite source, Graphics g) {
        DrawUtils.drawTopBar(g);
        text8.drawString2(g, "Thông tin cá nhân", GameColor.WHITE_CODE, Constants.SCREEN_WIDTH / 2, 4, Constants.TOP_HCENTER_ANCHOR);
      }
    }).setSize(Constants.SCREEN_WIDTH, 25);

    chooseIndex = 0;
    formDy = 0;
    isShowExtendInfo = false;
    SocketClientUtil.requestUserInfo(account);
    updateUserInfo(account);
    _manager.enableTouchPad();
  }

  public void updateUserInfo(String username) {
    User user = (User) Global.userCachedMap.get(username);
    if (user == null) {
      return;
    }
    if (statusTextField != null) {
      mobileTextField.setText(user.getMobile());
      statusTextField.setText(user.getStatus());
      dateOfBirthTextField.setText(user.getBirthDay());
      monthOfBirthTextField.setText(user.getBirthMonth());
      yearOfBirthTextField.setText(user.getBirthYear());
      emailTextField.setText(user.getEmail());
      addressTextField.setText(user.getAddress());
      if (user.getGender().equals("0")) {
        maleCheckbox.setChecked(true);
        femaleCheckbox.setChecked(false);
      } else {
        maleCheckbox.setChecked(false);
        femaleCheckbox.setChecked(true);
      }
    }
  }

  public void draw(Graphics g) {
    DrawUtils.drawBackground(g);

    // Draw user avatar
    User user = (User) Global.userCachedMap.get(account);
    if (user == null) {
      return;
    }
    g.setClip(0, 30, Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT - 60);
    g.clipRect(6, 34 + formDy - 1, 45, 45);
    g.drawImage(Global.getAvatar(user.getName()), 6, 34 + formDy, Constants.TOP_LEFT_ANCHOR);
    g.setClip(0, 30, Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT - 60);
    if (chooseIndex == 0) {
      g.setColor(GameColor.YELLOW_CODE);
    } else {
      g.setColor(GameColor.WHITE_CODE);
    }
    g.drawRect(6, 34 + formDy, 45, 45);
    g.setClip(0, 0, Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT);

    // Draw user name
    text8.drawString2(g, user.getName(), GameColor.WHITE_CODE, 61, 34 + formDy, Constants.TOP_LEFT_ANCHOR);

    // Draw status textfield
    statusTextField.draw(g);

    // Draw Point
    text8.drawString2(g, "Level: " + user.getLevel(), GameColor.WHITE_CODE, 7, 89 + formDy, Constants.TOP_LEFT_ANCHOR);
    if (!isShowExtendInfo) {
      text8.drawString2(g, "Thông tin thêm >>", GameColor.YELLOW_CODE, 90, 89 + formDy, Constants.TOP_LEFT_ANCHOR);
      if (chooseIndex == 2) {
        g.setColor(GameColor.YELLOW_CODE);
        g.drawLine(90, 105 + formDy, 90 + text8.stringWidth("Thông tin thêm"), 105 + formDy);
      }
    }

    if (!isShowExtendInfo) {
      drawInfo(g);
    } else {
      drawExtendedInfo(g);
    }
  }

  private void drawInfo(Graphics g) {
    setVisibleForAllComponent(true);
    User user = (User) Global.userCachedMap.get(account);
    if (user == null) {
      return;
    }

    // Draw Money
    text8.drawString2(g, "Tiền: ", GameColor.WHITE_CODE, 7, 106 + formDy, Constants.TOP_LEFT_ANCHOR);
    text8.drawString2(g, "" + user.getMoney(), GameColor.YELLOW_CODE, 44, 106 + formDy, Constants.TOP_LEFT_ANCHOR);

    // Draw Gold
    text8.drawString2(g, "Gold: ", GameColor.WHITE_CODE, 7, 128 + formDy, Constants.TOP_LEFT_ANCHOR);
    text8.drawString2(g, "" + user.getGold(), GameColor.YELLOW_CODE, 44, 128 + formDy, Constants.TOP_LEFT_ANCHOR);

    // Draw giới tính
    text8.drawString2(g, "Giới tính:", GameColor.WHITE_CODE, 7, 152 + formDy, Constants.TOP_LEFT_ANCHOR);
    maleCheckbox.draw(g);
    femaleCheckbox.draw(g);

    // Draw mobile number
    text8.drawString2(g, "Điện thoại:", GameColor.WHITE_CODE, 7, 178 + formDy, Constants.TOP_LEFT_ANCHOR);
    mobileTextField.draw(g);

    // Draw mobile number
    text8.drawString2(g, "Họ tên:", GameColor.WHITE_CODE, 7, 202 + formDy, Constants.TOP_LEFT_ANCHOR);
    fullNameTextField.draw(g);

    // Draw date of birth
    text8.drawString2(g, "Ngày sinh (dd/mm/yyyy):", GameColor.WHITE_CODE, 7, 228 + formDy, Constants.TOP_LEFT_ANCHOR);
    dateOfBirthTextField.draw(g);
    monthOfBirthTextField.draw(g);
    yearOfBirthTextField.draw(g);

    // Draw email
    text8.drawString2(g, "Email:", GameColor.WHITE_CODE, 7, 255 + formDy, Constants.TOP_LEFT_ANCHOR);
    emailTextField.draw(g);

    // Draw address
    text8.drawString2(g, "Địa chỉ:", GameColor.WHITE_CODE, 7, 281 + formDy, Constants.TOP_LEFT_ANCHOR);
    addressTextField.draw(g);

    if (account.equals(Global.currentUser.getName())) {
      if ((chooseIndex != 0) && (chooseIndex != 2) && (chooseIndex != 3) && (chooseIndex != 4)) {
        if (Global.currentUser.getName().equals(account)) {
          DrawUtils.getBottomBar(_manager).setCenterLabel("Cập nhật");
          DrawUtils.getBottomBar(_manager).setRightLabel("Xóa");
        }else{
          DrawUtils.getBottomBar(_manager).setCenterLabel("");
          DrawUtils.getBottomBar(_manager).setRightLabel("");
        }
      } else {
        DrawUtils.getBottomBar(_manager).setCenterLabel("Chọn");
        DrawUtils.getBottomBar(_manager).setRightLabel("Trở về");
      }
    }
  }

  private void setVisibleForAllComponent(boolean isVisible) {
    statusTextField.setVisible(isVisible);
    mobileTextField.setVisible(isVisible);
    fullNameTextField.setVisible(isVisible);
    dateOfBirthTextField.setVisible(isVisible);
    monthOfBirthTextField.setVisible(isVisible);
    yearOfBirthTextField.setVisible(isVisible);
    emailTextField.setVisible(isVisible);
    addressTextField.setVisible(isVisible);
    maleCheckbox.setVisible(isVisible);
    femaleCheckbox.setVisible(isVisible);
  }

  private void drawExtendedInfo(Graphics g) {
    setVisibleForAllComponent(false);

    User user = (User) Global.userCachedMap.get(account);
    if (user == null) {
      return;
    }

    // Draw Money
    text8.drawString2(g, "Kinh nghiệm: ", GameColor.WHITE_CODE, 7, 114 + formDy, Constants.TOP_LEFT_ANCHOR);
    text8.drawString2(g, user.getExperience() + "/" + user.getNextLevelExp(), GameColor.WHITE_CODE, 95, 114 + formDy, Constants.TOP_LEFT_ANCHOR);

    // Draw giới tính
    text8.drawString2(g, "Số trận thắng:", GameColor.WHITE_CODE, 7, 138 + formDy, Constants.TOP_LEFT_ANCHOR);
    text8.drawString2(g, user.getSoTranThang() + "/" + user.getTongSoTran(), GameColor.WHITE_CODE, 95, 138 + formDy, Constants.TOP_LEFT_ANCHOR);

    // Draw mobile number
    text8.drawString2(g, "Số trận thua:", GameColor.WHITE_CODE, 7, 162 + formDy, Constants.TOP_LEFT_ANCHOR);
    text8.drawString2(g, user.getSoTranThua() + "/" + user.getTongSoTran(), GameColor.WHITE_CODE, 95, 162 + formDy, Constants.TOP_LEFT_ANCHOR);

    // Draw bottom bar
    DrawUtils.getBottomBar(_manager).setCenterLabel("");
    DrawUtils.getBottomBar(_manager).setRightLabel("Trở về");
  }

  public void keyReleased(int keyCode) {
    if (isShowExtendInfo) {
      if (keyCode == Key.SOFT_RIGHT) {
        isShowExtendInfo = false;
      }
      return;
    }

    switch (keyCode) {
    case Key.DOWN:
      if (chooseIndex < 11) {
        chooseIndex++;
      }
      updateFocus();
      break;
    case Key.UP:
      if (chooseIndex > 0) {
        chooseIndex--;
      }
      updateFocus();
      break;
    case Key.SOFT_RIGHT:
    case Key.BACKSPACE:
      if (isShowExtendInfo) {
        isShowExtendInfo = false;
      } else {
        if ((chooseIndex != 0) && (chooseIndex != 2) && (chooseIndex != 3) && (chooseIndex != 4)) {
          clearLastChar();
        } else {
          if (goBackForm != null) {
            Global.nextState(goBackForm, parameters);
          } else {
            Global.nextState(FrmGroupMenu.instance(), parameters);
          }
        }
      }
      break;
    case Key.FIRE:
      if (!account.equals(Global.currentUser.getName())) { 
        return;
      }
      
      if (chooseIndex == 0) {
        Global.nextState(FrmChooseAvatar.instance(), null);
      } else if (chooseIndex == 2) {
        isShowExtendInfo = true;
      } else if (chooseIndex == 3 || chooseIndex == 4) {
        maleCheckbox.setChecked(!maleCheckbox.isChecked());
        femaleCheckbox.setChecked(!maleCheckbox.isChecked());
      } else {
        if (!Global.currentUser.getName().equals(account)) {
          return;
        }
        User newUserInfo = new User(account);
        newUserInfo.setGender(maleCheckbox.isChecked() ? "0" : "1");
        newUserInfo.setMobile(mobileTextField.getText());
        newUserInfo.setFullName(fullNameTextField.getText());
        newUserInfo.setBirthDay(dateOfBirthTextField.getText());
        newUserInfo.setBirthMonth(monthOfBirthTextField.getText());
        newUserInfo.setBirthYear(yearOfBirthTextField.getText());
        newUserInfo.setEmail(emailTextField.getText());
        newUserInfo.setAddress(addressTextField.getText());
        newUserInfo.setStatus(statusTextField.getText());
        SocketClientUtil.changeUserInfoRequest(newUserInfo);
      }
      break;
    default:
      transferKeyToTextField(keyCode);
      break;
    }
  }

  private void clearLastChar() {
    switch (chooseIndex) {
    case 1:
      statusTextField.deleteLastChar();
      break;
    case 5:
      mobileTextField.deleteLastChar();
      break;
    case 6:
      fullNameTextField.deleteLastChar();
      break;
    case 7:
      dateOfBirthTextField.deleteLastChar();
      break;
    case 8:
      monthOfBirthTextField.deleteLastChar();
      break;
    case 9:
      yearOfBirthTextField.deleteLastChar();
      break;
    case 10:
      emailTextField.deleteLastChar();
      break;
    case 11:
      addressTextField.deleteLastChar();
      break;
    }
  }

  private void updateFocus() {
    statusTextField.setFocused(false);
    maleCheckbox.setFocused(false);
    femaleCheckbox.setFocused(false);
    mobileTextField.setFocused(false);
    fullNameTextField.setFocused(false);
    dateOfBirthTextField.setFocused(false);
    monthOfBirthTextField.setFocused(false);
    yearOfBirthTextField.setFocused(false);
    emailTextField.setFocused(false);
    addressTextField.setFocused(false);

    switch (chooseIndex) {
    case 1:
      statusTextField.setFocused(true);
      moveToFocusToComponent(40 - statusTextField.getRealY());
      break;
    case 3:
      maleCheckbox.setFocused(true);
      moveToFocusToComponent(40 - maleCheckbox.getRealY());
      break;
    case 4:
      femaleCheckbox.setFocused(true);
      moveToFocusToComponent(40 - femaleCheckbox.getRealY());
      break;
    case 5:
      mobileTextField.setFocused(true);
      moveToFocusToComponent(40 - mobileTextField.getRealY());
      break;
    case 6:
      fullNameTextField.setFocused(true);
      moveToFocusToComponent(40 - fullNameTextField.getRealY());
      break;
    case 7:
      dateOfBirthTextField.setFocused(true);
      moveToFocusToComponent(40 - dateOfBirthTextField.getRealY());
      break;
    case 8:
      monthOfBirthTextField.setFocused(true);
      moveToFocusToComponent(40 - monthOfBirthTextField.getRealY());
      break;
    case 9:
      yearOfBirthTextField.setFocused(true);
      moveToFocusToComponent(40 - yearOfBirthTextField.getRealY());
      break;
    case 10:
      emailTextField.setFocused(true);
      moveToFocusToComponent(40 - emailTextField.getRealY());
      break;
    case 11:
      addressTextField.setFocused(true);
      moveToFocusToComponent(40 - addressTextField.getRealY());
      break;
    }
  }

  private void transferKeyToTextField(int keyCode) {
    switch (chooseIndex) {
    case 1:
      statusTextField.keyReleased1(keyCode);
      break;
    case 5:
      mobileTextField.keyReleased1(keyCode);
      break;
    case 6:
      fullNameTextField.keyReleased1(keyCode);
      break;
    case 7:
      dateOfBirthTextField.keyReleased1(keyCode);
      break;
    case 8:
      monthOfBirthTextField.keyReleased1(keyCode);
      break;
    case 9:
      yearOfBirthTextField.keyReleased1(keyCode);
      break;
    case 10:
      emailTextField.keyReleased1(keyCode);
      break;
    case 11:
      addressTextField.keyReleased1(keyCode);
      break;
    }
  }

  public void onActionPerform(Event event) {
    // "Về menu chính", "Bạn bè", "Đổi mật khẩu", "Chọn avatar", "Đổi gold"
    String action = event.getAction();
    if (action.equals("Về menu chính")) {
      Global.nextState(FrmGroupMenu.instance(), null);
    } else if (action.equals("Bạn bè")) {
      Global.nextState(FrmGroupFriendAndTop.instance(), null);
      FrmGroupFriendAndTop.backForm = FrmUserInfo.instance();
    } else if (action.equals("Đổi mật khẩu")) {
      Global.nextState(FrmChangePassword.instance(), null);
    } else if (action.equals("Chọn avatar")) {
      Global.nextState(FrmChooseAvatar.instance(), null);
    } else if (action.equals("Đổi gold")) {
      FrmGroupNapXuAndExchangeGold.backForm = this;
      Global.nextState(FrmGroupNapXuAndExchangeGold.instance(), null);
      FrmGroupNapXuAndExchangeGold.setTab(1);
    }
  }

  private void moveToFocusToComponent(int dy) {
    formDy += dy;
    statusTextField.move(0, dy);
    mobileTextField.move(0, dy);
    fullNameTextField.move(0, dy);
    dateOfBirthTextField.move(0, dy);
    monthOfBirthTextField.move(0, dy);
    yearOfBirthTextField.move(0, dy);
    emailTextField.move(0, dy);
    addressTextField.move(0, dy);
    maleCheckbox.move(0, dy);
    femaleCheckbox.move(0, dy);
  }

  public void destroy() {
    statusTextField = null;
    mobileTextField = null;
    fullNameTextField = null;
    dateOfBirthTextField = null;
    monthOfBirthTextField = null;
    yearOfBirthTextField = null;
    emailTextField = null;
    addressTextField = null;
    maleCheckbox = null;
    femaleCheckbox = null;
    text8 = null;
    parameters = null;
    account = null;
    formDy = 0;
  }
}
